import { Modal, Form, Input, Button, message, Icon } from "antd";
import moment from "moment";
import React from "react";
import ColorPicker from './colorCustom';
import { getKnowledgeTagDetail, postKnowledgeTagAdd, postKnowledgeTagEdit } from "@/services/knowledgeLabel";

let tag_id = 1;
class EditLabel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      title: '添加知识标签',
      loading: false,
      id: null,
      tagDetail: null,
    };
    this.ColorPickerRef = React.createRef();
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
    }
  }

  onOpenDrawer = row => {
    this.setState({
      visible: true,
      title: row ? '编辑知识标签' : '添加知识标签',
      id: row ? row.id : null
    }, () => {
      if (row && row.id) {
        this.getDetail()
      } else {
        setTimeout(() => {
          if (this.ColorPickerRef) {
            this.ColorPickerRef.current.setColor("#FF0000");
          };
        }, 50)
      }
    })
  }

  getDetail = async () => {
    const { id } = this.state;
    const form = this.props.form;
    const res = await getKnowledgeTagDetail({ id });
    console.log(res);
    let tagList = [];
    if (res.tagList && res.tagList.length) {
      res.tagList.forEach((item, index) => {
        tagList.push({ id: index, key: item.id, value: item.tagValue });
      });
    };
    tag_id = res.tagList && res.tagList.length > 0 ? res.tagList.length : 1;
    this.setState({ tagDetail: res, }, () => {
      form.setFieldsValue({
        tagName: res.tagTypeValue,
        id: res.id,
        tagColor: res.tagColor,
        tagList: tagList,
      });
    })
    if (this.ColorPickerRef) {
      this.ColorPickerRef.current.setColor(res.tagColor);
    };
  }

  onClose = () => {
    this.props.form.resetFields()
    this.setState({
      visible: false,
      title: '添加知识标签',
      loading: false,
      id: null,
      tagDetail: null,
    })
  }

  doSubmit = () => {
    const that = this;
    const { id } = this.state;
    const formInfo = this.props.form.getFieldsValue();
    console.log(formInfo);
    let params = {
      tagTypeValue: formInfo.tagName,
      tagColor: formInfo.tagColor ? formInfo.tagColor : "#FF0000",
      tagList: formInfo.tagList.map(item => ({
        id: item.key,
        tagValue: formInfo.tagValue[item.id],
      }))
    };
    that.props.form.validateFields((err, values) => {
			if (!err) {
        let list = params.tagList.filter(item => item.tagValue)
        if (list.length < 1) {
          return message.error('标签值不能为空，请添加标签值')
        };
        that.setState({ loading: true }, async () => {
          let res;
          if (id) {
            params.id = id;
            res = await postKnowledgeTagEdit(params)
          } else {
            res = await postKnowledgeTagAdd(params)
          };
          console.log(res);
          if (res && res.code == 0) {
            message.info(res.msg);
            that.setState({ visible: false }, () => {
              that.onClose();
              that.props.refreshList()
            });
          } else {
            // 保存失败，只关闭loading
          }
          that.setState({ loading: false })
        })
      }
    })
  }

  add = () => {
    const { form } = this.props;
    const tagList = form.getFieldValue('tagList');
    const nextKeys = tagList.concat({ id: tag_id++, key: null, value: '' });
    form.setFieldsValue({ tagList: nextKeys });
  };

  remove = k => {
    const { form } = this.props;
    const tagList = form.getFieldValue('tagList');
    if (tagList.length === 1) {
      return;
    };
    form.setFieldsValue({
      tagList: tagList.filter(key => key !== k),
    });
  };

  render() {
    const { visible, title, loading, id, tagDetail } = this.state;
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
    };
    getFieldDecorator('tagList', { initialValue: [{ id: 0, key: null, value: '' }] });
    const tagList = getFieldValue('tagList');

    return (
      <Modal
        visible={visible}
        title={title}
        onCancel={this.onClose}
        destroyOnClose
        footer={[
          <Button onClick={this.onClose}>取消</Button>,
          <Button type="primary" onClick={this.doSubmit}>确定</Button>,
        ]}
      >
        <Form {...formItemLayout} style={{ marginBottom: 60 }}>
          <Form.Item label="标签类型">
            {getFieldDecorator('tagName', { rules: [{ required: true, message: '请填写标签类型' }] })(
              <Input placeholder="请输入" />
            )}
          </Form.Item>

          <Form.Item label="标签颜色">
            {getFieldDecorator('tagColor', {
              // initialValue: tagDetail?.tagColor,
              rules: [{ required: true, message: '请填写标签类型' }]
            })(
              <ColorPicker
                color={tagDetail && tagDetail.tagColor ? tagDetail.tagColor : "#FF0000"}
                onChange={(color) => setFieldsValue({ tagColor: color })}
                ref={this.ColorPickerRef}
              />
            )}
          </Form.Item>

          <Form.Item label="标签值">
            {tagList.map((item, index) => {
              return (
                <div
                  key={index}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '12px',
                    marginRight: 20,
                    marginBottom: 12,
                  }}
                >
                  {getFieldDecorator(`tagValue[${item.id}]`, {
                    initialValue: item.value,
                  })(<Input placeholder="请输入" style={index == 0 ? { width: 'calc(100% - 30px)' } : {}} />)}
                  {tagList.length > 1 && index >= 1 ? (
                    <Icon
                      className="dynamic-delete-button"
                      type="minus-circle-o"
                      style={{ fontSize: '18px', color: 'red', }}
                      onClick={() => this.remove(item)}
                    />
                  ) : null}
                </div>
              )
            })}
            <Button type="dashed" onClick={this.add} style={{ width: 'calc(100% - 50px)' }}><Icon type="plus" /> 添加标签值</Button>
          </Form.Item>
        </Form>
      </Modal>
    )
  }
}

export default Form.create()(EditLabel)
